package cn.iocoder.yudao.module.member.service.newsStudyInfo;

import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.util.MyBatisUtils;
import cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils;
import cn.iocoder.yudao.module.member.controller.admin.newsStudyInfo.vo.*;
import cn.iocoder.yudao.module.member.convert.newsStudyInfo.NewsStudyInfoConvert;
import cn.iocoder.yudao.module.member.dal.dataobject.newsStudyInfo.NewsStudyInfoDO;
import cn.iocoder.yudao.module.member.dal.dataobject.newsStudyInfo.NewsStudyRankingDO;
import cn.iocoder.yudao.module.member.dal.dataobject.newsStudyType.NewsStudyTypeDO;
import cn.iocoder.yudao.module.member.dal.mysql.newsStudyInfo.NewsStudyInfoMapper;
import cn.iocoder.yudao.module.member.dal.mysql.newsStudyInfo.NewsStudyRankingMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.*;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.NEWS_STUDY_INFO_NOT_EXISTS;

/**
 * 新闻信息(成果信息) Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class NewsStudyInfoServiceImpl implements NewsStudyInfoService  {
    @Resource
    private NewsStudyInfoMapper newsStudyInfoMapper;
    @Resource
    private NewsStudyRankingMapper newsStudyRankingMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createNewsStudyInfo(NewsStudyInfoCreateReqVO createReqVO) {
        // 插入
        NewsStudyInfoDO newsStudyInfo = NewsStudyInfoConvert.INSTANCE.convert(createReqVO);
        newsStudyInfo.setCreator(WebFrameworkUtils.getLoginUserName());
        newsStudyInfo.setUpdater(WebFrameworkUtils.getLoginUserName());
        newsStudyInfoMapper.insert(newsStudyInfo);
        return newsStudyInfo.getId();
    }

    @Override
    public void updateNewsStudyInfo(NewsStudyInfoUpdateReqVO updateReqVO) {
        // 校验存在
        NewsStudyInfoDO newsStudyInfoDO = newsStudyInfoMapper.selectById(updateReqVO.getId());
        if(null==newsStudyInfoDO){
            throw exception(NEWS_STUDY_INFO_NOT_EXISTS);
        }
        // 更新
        NewsStudyInfoDO updateObj = NewsStudyInfoConvert.INSTANCE.convert(updateReqVO);
        if("0".equals(newsStudyInfoDO.getStatus()) && "1".equals(updateReqVO.getStatus())){
            updateObj.setReleaseTime(new Date());
        }
        updateObj.setUpdater(WebFrameworkUtils.getLoginUserName());
        newsStudyInfoMapper.updateById(updateObj);
    }

    @Override
    public void updateTopping(Long id,Integer isTop) {
//        Integer maxWeight = newsStudyInfoMapper.getNewsStudyWeight(type);
        NewsStudyInfoDO updateObj=new NewsStudyInfoDO();
        updateObj.setId(id);
        updateObj.setIsTop(isTop);
        updateObj.setUpdateTime(new Date());
        updateObj.setUpdater(WebFrameworkUtils.getLoginUserName());
        newsStudyInfoMapper.updateById(updateObj);
    }

    @Override
    public void deleteNewsStudyInfo(Long id) {
        // 校验存在
        int i = newsStudyInfoMapper.deleteById(id);
        if (i == 0) {
            throw exception(NEWS_STUDY_INFO_NOT_EXISTS);
        }

    }

    @Override
    public boolean updateBatch(NewsStudyInfoIdReqVO newsStudyInfoIdReqVO) {
        List<Long> ids = newsStudyInfoIdReqVO.getIds();
        //批量发布(release),批量不发布(noRelease),批量删除(delete),批量更换栏目(typeIds),批量还原(recovery)
        String operate=newsStudyInfoIdReqVO.getOperate();
        String status=null;
        Long typeId=null;
        Boolean deleted=null;
        if("month".equals(operate)){
            List<NewsStudyRankingDO> list=new ArrayList<>();
            Integer newsStudyWeight = newsStudyRankingMapper.getNewsStudyWeight();
            for (int i = 0; i <ids.size() ; i++) {
                int num = newsStudyRankingMapper.getNewsRankingInfoExist(ids.get(i), 2);
                if(num>0){
                    continue;
                }
                NewsStudyRankingDO newsStudyRankingDO=new NewsStudyRankingDO();
                newsStudyRankingDO.setNewsId(ids.get(i));
                newsStudyRankingDO.setType(2);
                newsStudyRankingDO.setWeight(newsStudyWeight+i);
                list.add(newsStudyRankingDO);
            }
            newsStudyRankingMapper.insertBatch(list);
            return true;
        }else if("week".equals(operate)){
            List<NewsStudyRankingDO> list=new ArrayList<>();
            Integer newsStudyWeight = newsStudyRankingMapper.getNewsStudyWeight();
            for (int i = 0; i <ids.size() ; i++) {
                int num = newsStudyRankingMapper.getNewsRankingInfoExist(ids.get(i), 1);
                if(num>0){
                    continue;
                }
                NewsStudyRankingDO newsStudyRankingDO=new NewsStudyRankingDO();
                newsStudyRankingDO.setNewsId(ids.get(i));
                newsStudyRankingDO.setType(1);
                newsStudyRankingDO.setWeight(newsStudyWeight+i);
                list.add(newsStudyRankingDO);
            }
            newsStudyRankingMapper.insertBatch(list);
            return true;
        }else if("release".equals(operate)){
            status="1";
        }else if("noRelease".equals(operate)){
            status="0";
        }else if("delete".equals(operate)){
            deleted=true;
        }else if("recovery".equals(operate)){
            deleted=false;
            typeId=newsStudyInfoIdReqVO.getTypeId();
        }else if("typeIds".equals(operate)){
            typeId=newsStudyInfoIdReqVO.getTypeId();
            if (typeId == null) {
                ErrorCode errorCode=new ErrorCode(1004008003, "类型ID不存在");
                throw exception(errorCode);
            }
        }
        newsStudyInfoMapper.updateNewsStudyInfo(status,typeId,deleted,ids);
        return true;
    }

    private void validateNewsStudyInfoExists(Long id) {
        if (newsStudyInfoMapper.selectById(id) == null) {
            throw exception(NEWS_STUDY_INFO_NOT_EXISTS);
        }
    }

    @Override
    public NewsStudyInfoDO getNewsStudyInfo(Long id) {
        return newsStudyInfoMapper.selectById(id);
    }

    @Override
    public List<NewsStudyInfoDO> getNewsStudyInfoList(Collection<Long> ids) {
        return newsStudyInfoMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<NewsStudyInfoDO> getNewsStudyInfoPage(NewsStudyInfoPageReqVO pageReqVO) {
        // MyBatis Plus 查询
        IPage<NewsStudyInfoDO> mpPage = MyBatisUtils.buildPage(pageReqVO);
        // 转换返回
        Map<String, Object> params = new HashMap<>();
        if(StringUtils.isNotBlank(pageReqVO.getTitle())){
            params.put("title",pageReqVO.getTitle());
        }
        if(null !=pageReqVO.getType()){
            params.put("type",pageReqVO.getType());
        }
        if(null !=pageReqVO.getTypeId()){
            params.put("typeId",pageReqVO.getTypeId());
        }
        if(null !=pageReqVO.getStatus()){
            params.put("status",pageReqVO.getStatus());
        }
        if(null !=pageReqVO.getIsTop()){
            params.put("isTop",pageReqVO.getIsTop());
        }
        if(StringUtils.isNotBlank(pageReqVO.getQueryDetail())){
            params.put("queryDetail",pageReqVO.getQueryDetail());
        }
        if(null !=pageReqVO.getDeleted()){
            params.put("deleted",pageReqVO.getDeleted());
        }else{
            params.put("deleted",0);
        }
        mpPage.setRecords(newsStudyInfoMapper.getNewsStudyInfoList(mpPage, params));
        return new PageResult<>(mpPage.getRecords(), mpPage.getTotal());
    }

    @Override
    public List<NewsStudyInfoDO> getNewsStudyInfoList(NewsStudyInfoExportReqVO exportReqVO) {
        return newsStudyInfoMapper.selectList(exportReqVO);
    }

    @Override
    public List<NewsStudyRankingDO> getNewsStudyRankingList(Integer type) {
        return newsStudyRankingMapper.getNewsStudyRankingList(type);
    }

    @Override
    public void deleteNewsRankingInfo(String queryType,Long id, Integer type ) {
        newsStudyRankingMapper.deleteNewsRankingInfo(queryType,id,type);
    }

    @Override
    public void rankingInfoSort(NewsStudyRankingIdReqVO rankingIdReqVO) {
        List<Long> ids = rankingIdReqVO.getIds();
        List<NewsStudyRankingDO> list=new ArrayList<>();
        for (int i = 0; i < ids.size(); i++) {
            NewsStudyRankingDO r=new NewsStudyRankingDO();
            r.setId(ids.get(i));
            r.setWeight(i+1);
            list.add(r);
        }
        newsStudyRankingMapper.rankingInfoSort(list);
    }

    @Override
    public NewsStudyInfoDO getNewsStudyInfoById(Long id) {
        return newsStudyInfoMapper.getNewsStudyInfoById(id);
    }

    @Override
    public void updateViewNum(Long id) {
        newsStudyInfoMapper.updateViewNum(id);
    }
}
